﻿using System;
using System.Collections.Generic;
using System.Web;
using Newtonsoft.Json;
using BrnMall.WeiXin.Sdk.Domain;
using BrnMall.Sdk.WeiXin.Domain.work;

namespace BrnMall.WeiXin.Sdk.Work
{
    public class WorkWeiXinSDK
    {
        #region 安装应用授权
        /// <summary>
        /// 获取应用套件凭证
        /// </summary>
        /// <param name="suite_ticket"></param>
        /// <returns>应用套件凭证,最长为512字节</returns>
        protected static Suite_Token Get_Suite_Token(string suite_ticket,string suite_id,string suite_secret)
        {
            /*
             suite_id：应用套件id
             suite_secret：应用套件secret
             suite_ticket：由企业微信后台定时推送给应用套件，并每十分钟更新，请用最新的suite_ticket。
             */

            var obj = new { suite_id = suite_id, suite_secret = suite_secret, suite_ticket = suite_ticket };
            string param = JsonConvert.SerializeObject(obj);
            var html = Http.RequestPost("https://qyapi.weixin.qq.com/cgi-bin/service/get_suite_token", param);
            return JsonConvert.DeserializeObject<Suite_Token>(html);
        }

        /// <summary>
        /// 获取预授权码
        /// </summary>
        /// <param name="tokenModel">应用套件凭证</param>
        /// <returns></returns>
        public static PreAuthCode Get_Pre_Auth_Code(Suite_Token tokenModel)
        {
            var url = string.Format("https://qyapi.weixin.qq.com/cgi-bin/service/get_pre_auth_code?suite_access_token={0}", tokenModel.suite_access_token);
            var html = Http.RequestGet(url);
            return JsonConvert.DeserializeObject<PreAuthCode>(html);
        }

        /// <summary>
        /// 设置授权配置
        /// </summary>
        /// <param name="authCode"></param>
        /// <returns></returns>
        public static string set_session_info(Suite_Token suiteToken, PreAuthCode authCode, int auth_type = 0)
        {
            var obj = new
            {
                pre_auth_code = authCode.pre_auth_code,
                session_info = new { auth_type = auth_type }
            };
            var param = JsonConvert.SerializeObject(obj);
            var url = string.Format(" https://qyapi.weixin.qq.com/cgi-bin/service/set_session_info?suite_access_token={0}", suiteToken.suite_access_token);
            var html = Http.RequestPost(url, param);
            return html;
        }

        /// <summary>
        /// 获取企业永久授权码
        /// </summary>
        /// <param name="autoCodeModel">预授权码</param>
        /// <returns></returns>
        public static PermanentCode Get_Permanent_Code(string authCode, Suite_Token suiteToken)
        {
            var obj = new { auth_code = authCode };
            var param = JsonConvert.SerializeObject(obj);
            var url = string.Format("https://qyapi.weixin.qq.com/cgi-bin/service/get_permanent_code?suite_access_token={0}", suiteToken.suite_access_token);
            var html = Http.RequestPost(url, param);

            Log("获取永久授权码返回:" + html);

            return JsonConvert.DeserializeObject<PermanentCode>(html);
        }

        /// <summary>
        /// 获取企业access_token
        /// </summary>
        /// <param name="tokenModel"></param>
        /// <param name="permanent_code">永久授权码</param>
        /// <param name="auth_corpid">授权人的corpid,在获取永久授权码的内容中获取</param>
        /// <returns></returns>
        public static AccessToken get_corp_token(Suite_Token tokenModel, string permanent_code, string auth_corpid,string suite_id)
        {
            var param = string.Format("{{\"suite_id\":\"{0}\",\"auth_corpid\":\"{1}\",\"permanent_code\":\"{2}\"}}", suite_id, auth_corpid, permanent_code);
            var url = string.Format("https://qyapi.weixin.qq.com/cgi-bin/service/get_corp_token?suite_access_token={0}", tokenModel.suite_access_token);
            var html = Http.RequestPost(url, param);
            return JsonConvert.DeserializeObject<AccessToken>(html);
        }

        /// <summary>
        /// 获取安装应用的路径
        /// </summary>
        public static string GetInstallUrl(PreAuthCode autoCode, string state, string storeId, string suite_id, string redirect_uri)
        {
            return string.Format("https://open.work.weixin.qq.com/3rdapp/install?suite_id={0}&pre_auth_code={1}&state={3}&redirect_uri={2}",
                suite_id,
                autoCode.pre_auth_code,
                HttpUtility.UrlEncode(redirect_uri + storeId), state
                );
        }
        #endregion

        #region 发送消息
        /// <summary>
        /// 发送文本消息
        /// </summary>
        /// <param name="content">消息内容，可以带超链接格式</param>
        /// <param name="touser">接收的用户,多个接收者用‘|’分隔，最多支持1000个</param>
        /// <param name="agentid">企业应用的ID</param>
        /// /// <param name="access_token">企业的access_token</param>
        /// <returns></returns>
        public static string SendTextMessage(string content, string touser, int agentid, string access_token)
        {
            var contentModel = new TextMessageContentModel() { content = content };
            var model = new MessageModel()
            {
                agentid = agentid,
                text = contentModel,
                touser = touser,
                toparty = "",
                totag = "",
                media_id = "",
                msgtype = "text",
                safe = 0
            };
            return SendMessage(model, access_token);
        }

        public static string SendMessage(MessageModel model, string access_token)
        {
            var param = JsonConvert.SerializeObject(model);
            var url = string.Format("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={0}", access_token);
            var html = Http.RequestPost(url, param);
            return html;
        }
        #endregion

        #region 部门管理

        /// <summary>
        /// 获取部门列表
        /// </summary>
        /// <param name="access_token">企业access_token</param>
        /// <param name="id">部门id。获取指定部门及其下的子部门。 如果不填，默认获取全量组织架构</param>
        public static DepartmentListModel GetDepartmentList(string access_token, string id)
        {
            var url = string.Format("https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token={0}&id={1}", access_token, id);
            var html = Http.RequestGet(url);
            return JsonConvert.DeserializeObject<DepartmentListModel>(html);
        }
        /// <summary>
        /// 创建部门
        /// </summary>
        /// <param name="access_token"></param>
        /// <param name="name"></param>
        /// <param name="parentid"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static int CreateDepartment(string access_token, string name, int parentid, int id = 0)
        {
            var obj1 = new { name = name, parentid = parentid };
            var obj2 = new { name = name, parentid = parentid, id = id };

            var param = id > 0 ? JsonConvert.SerializeObject(obj2) : JsonConvert.SerializeObject(obj1);
            var url = string.Format("https://qyapi.weixin.qq.com/cgi-bin/department/create?access_token={0}", access_token);
            var html = Http.RequestPost(url, param);
            //创建成功，返回部门ID
            var json = JsonConvert.DeserializeObject<ReturnModel>(html);
            if (json != null && json.errcode == 0)
                return json.id;
            return 0;
        }
        #endregion

        #region 员工管理
        /// <summary>
        /// 取部门成员列表
        /// </summary>
        /// <param name="access_token"></param>
        /// <param name="department_id">部门id</param>
        /// <param name="fetch_child">是否递归获取子部门下面的成员（1 递归，0 不递归）</param>
        /// <returns></returns>
        public static UserListListModel GetUserList(string access_token, string department_id, int fetch_child = 1)
        {
            var url = string.Format("https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?access_token={0}&department_id={1}&fetch_child={2}", access_token, department_id, fetch_child);
            var html = Http.RequestGet(url);
            return JsonConvert.DeserializeObject<UserListListModel>(html);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="access_token"></param>
        /// <param name="userid">成员UserID，企业内必须唯一。不区分大小写</param>
        /// <returns></returns>
        public static UserDetail GetUser(string access_token, string userid)
        {
            var url = string.Format("https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token={0}&userid={1}", access_token, userid);
            var html = Http.RequestGet(url);
            return JsonConvert.DeserializeObject<UserDetail>(html);
        }


        #endregion

        #region 网页授权登录
        /// <summary>
        /// 网页授权登录：步骤一
        /// </summary>
        /// <returns></returns>
        public static string authorize(string corpId, string agentid, string redirect_uri)
        {
            var url = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope={2}&state=STATE#wechat_redirect",
                corpId, 
                redirect_uri,
                "snsapi_base");
            return url;
        }

        /// <summary>
        /// 网页授权登录：步骤二
        /// </summary>
        /// <returns></returns>
        public static OauthUser GetOauthUser(string access_token, string code)
        {
            var url = string.Format("https://qyapi.weixin.qq.com/cgi-bin/service/getuserinfo3rd?access_token={0}&code={1}", access_token, code);
            var html = Http.RequestGet(url);
            return JsonConvert.DeserializeObject<OauthUser>(html);
        }


        public static string GetOauthUserByString(string access_token, string code)
        {
            var url = string.Format("https://qyapi.weixin.qq.com/cgi-bin/service/getuserinfo3rd?access_token={0}&code={1}", access_token, code);
            return Http.RequestGet(url);
        }
        #endregion

        static void Log(string str)
        {
            //var path = HttpContext.Current.Server.MapPath("/log/") + "install.log";
            //using (System.IO.StreamWriter sw = new System.IO.StreamWriter(path, true))
            //{
            //    sw.WriteLine("\r" + DateTime.Now.ToString() + " \t" + str);
            //}
        }
    }
}